<template>
  <div>

    <div class="mt-[32px]">
      <el-form label-width="85px" :rules="rules" :model="form" ref="FormRef">
        <el-form-item :label="item.name" :prop="item.code"
                      v-for="(item,index) in config"
                      :key="index"
        >

          <el-input v-model="form[item.code]"
                    v-if="!item.type"
          />
          <el-select v-model="form[item.code]"
                     v-if="item.type == 'select'"
                     @change="onChange(item.code)"
          >
            <el-option v-for="(it,idx) in item.list" :key="idx"
                       :label="it[item.label]" :value="it[item.value]"
            />
          </el-select>

          <UploadImg v-model="form[item.code]" v-if="item.type == 'upload'"/>

        </el-form-item>
      </el-form>
    </div>

  </div>
</template>
<script setup lang="ts">
import UploadImg from "@/components/UploadFile/src/UploadImg.vue"
import Icon from "@/components/Icon/src/Icon.vue";
import {listToMap, formError, deepCopy} from "@/utils";
import {GlobeStateApi} from "@/api/logistics/globestate";
import {GlobeStateMethodApi} from "@/api/method";
import {GlobeStateDetailApi} from "@/api/globestatedetail";
import {GlobeStateHarvestVO, GlobeStateHarvestApi} from "@/api/address";
import { getGlobeState } from '@/api/publicInterf'

const props = defineProps({
  info: {
    type: Object,
    required: false,
    default: () => {
    }
  }
})

const FormRef = ref(null);

const provinceData = ref([])

const config = ref([
  {
    name: "地区",
    code: "detailStateId",
    required: true,
    type: "select",
    label: "stateName",
    value: "id",
    list: []
  },
  {
    name: "物流方式",
    code: "methodId",
    required: true,
    type: "select",
    list: [],
    label: "methodName",
    value: "id",
  },
  {
    name: "门店名称",
    code: "storeName",
    required: true,
  },
  {
    name: "一级区域",
    code: "province",
    required: true,
    type: "select",
    label: "name",
    value: "name",
  },
  {
    name: "二级区域",
    code: "city",
    type: "select",
    required: true,
    label: "name",
    value: "name",
  },

  {
    name: "详细地址",
    code: "detailedAddress",
  },
  {
    name: "联系电话",
    code: "phone",
  },
  {
    name: "关店时间",
    code: "closureTime"
  },
])

const rules = computed(() => {
  let map = listToMap(config.value, 'code');

  for (let i in map) {
    if (map[i].required) {
      if (map[i].type == 'select' || map[i].type == 'upload') {
        map[i] = [{required: true, message: `请选择${map[i].name}`, trigger: 'change'}]
      } else {
        map[i] = [{required: true, message: `请输入${map[i].name}`, trigger: 'blur'}]
      }
    }

  }
  return map
})


const form = ref({})

const confirm = async (callback) => {

  try {
    let res = await FormRef.value.validate();


    let option = {
      ...form.value,

    }
    let item = config.value.find(at => {
      return at.code == "detailStateId"
    })

    let it = item.list.find(at => {
      return at.id == form.value.detailStateId
    })
    option = {
      ...option,
      stateName: it.stateName,
    }

    item = config.value.find(at => {
      return at.code == "methodId"
    })
    it = item.list.find(at => {
      return at.id == form.value.methodId
    })

    option = {
      ...option,
      methodName: it.methodName
    }


    if (form.value.id) {
      await GlobeStateHarvestApi.updateGlobeStateHarvest(option);
    } else {
      await GlobeStateHarvestApi.createGlobeStateHarvest(option);
    }
    callback && callback()
  } catch (e) {
    formError()
  }

}

const onChange = code => {
  if (code == "detailStateId") {
    form.value.methodId = "";
    form.value.province = "";
    form.value.city = "";

    initPromise();
  } else if (code == "province") {

    form.value.city = ""
    let item = config.value.find(at => {
      return at.code == "city"
    })

    let list = provinceData.value.find(item => {
      return item.name == form.value.province
    })?.list || []

    item.list = list;

  }
}


const initPromise = async () => {
  let res = await Promise.all([GlobeStateMethodApi.getGlobeStateMethodPage({
    stateId: form.value.detailStateId,
    directlyStatus: 0
  }), GlobeStateDetailApi.getGlobeStateDetailPage({
    stateId: form.value.detailStateId
  })])

  let item = config.value.find(item => {
    return item.code == "methodId"
  })

  item.list = res[0].list;

  item = config.value.find(at => {
    return at.code == "province"
  })
  item.list = generateProvince(res[1]);
  provinceData.value = deepCopy(item.list);
}


/**
 * 生成省市区树
 * */
const generateProvince = (provinceData) => {
  console.log(provinceData)
  let cityList = [];
  provinceData.list.forEach(item => {
    let isIn = cityList.find(at => {
      return item.province == at.name
    })
    if (!isIn) {
      cityList.push({
        name: item.province,
        list: []
      })
    }
  })

  cityList.forEach(item => {
    let lis = provinceData.list.filter(it => {
      return it.province == item.name
    })

    item.list = (lis || []).map(item => {
      return {
        name: item.city,
        list: []
      }
    });


  })

  return cityList
}


const getAreaList = async () => {
  let res = await getGlobeState();
  let item = config.value.find(at => {
    return at.code == "detailStateId"
  })
  item.list = res || [];

}

onMounted(() => {
  getAreaList();
})

defineExpose({
  confirm
})

watch(() => props.info, () => {
  form.value = props.info;
  if (form.value.id) {
    initPromise();
    //onChange('detailStateId')
  }
}, {
  deep: true,
  immediate: true
})
</script>
<style lang="scss" scoped>

</style>
